package cn.xiaobai.captcha.server;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.json.JSONUtil;
import cn.xiaobai.captcha.domain.CaptchaResult;
import cn.xiaobai.captcha.handler.captchatype.AbstractCaptchaAbstractTypeHandler;
import cn.xiaobai.captcha.handler.dbtype.AbstractDBAbstractTypeHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Objects;

/**
 * 验证码生成适配器服务
 *
 * @Author yangdaji
 * @Date 2024/4/18
 * @PackageName cn.xiaobai.captcha.server
 * @ClassName CaptchaGeneralAdapterServer
 */
@Slf4j
public class CaptchaGeneralAdapterServer {


    /**
     * 数据库类型处理器
     */
    @Autowired(required = false)
    private AbstractDBAbstractTypeHandler dbTypeHandler;

    /**
     * 验证码类型处理器
     */
    @Autowired
    private AbstractCaptchaAbstractTypeHandler typeHandler;


    public String createGeneral(String unique) {
        CaptchaResult captchaResult = new CaptchaResult();
        // 生成验证码
        String newUnique = DigestUtil.md5Hex(unique);
        String handCaptchaGeneral = typeHandler.createGeneral();
        log.info("生成的验证码: {}", handCaptchaGeneral);
        if (Objects.nonNull(handCaptchaGeneral) && Objects.nonNull(dbTypeHandler)) {
            // 缓存验证码
            dbTypeHandler.captchaCache(newUnique, handCaptchaGeneral);
            captchaResult.setUnique(newUnique);
            captchaResult.setCaptcha(handCaptchaGeneral);
        }
        return JSONUtil.toJsonStr(captchaResult);
    }
}
